package io.renren.core.interceptor;

import cn.hutool.json.JSONUtil;
import io.renren.entity.WxUser;
import io.renren.utils.Constant;
import io.renren.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Slf4j
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //查看是否又user用户，如果没有则进行授权
        WxUser wxUser = (WxUser) request.getSession().getAttribute(Constant.SESSION_USER_KEY);

        if (wxUser != null) {
            return true;
        }

        if (request.getHeader("x-requested-with") != null
                && request.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
            // 抛出未授权异常
            R result = R.error(HttpStatus.UNAUTHORIZED.value(), "没有权限");
            responseResult(response, result);
        } else {
            //非ajax请求时，重定向到授权页面
            String accessUrl = request.getScheme() + "://" + request.getServerName() + request.getRequestURI();
            if (request.getQueryString() != null) {
                accessUrl = accessUrl + "?" + request.getQueryString();
            }

            response.sendRedirect(request.getContextPath() + "/api/wechat/authorize?returnUrl=" + accessUrl);
        }

        return false;
    }

    private void responseResult(HttpServletResponse response, R result) {
        response.setCharacterEncoding("UTF-8");
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        response.setStatus(200);
        try {
            response.getWriter().write(JSONUtil.toJsonStr(result));
        } catch (IOException ex) {
            log.error("拦截器响应异常================>" + ex.getMessage());
        }
    }
}
